package com.classroom.smart.controller;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.classroom.smart.constant.MessageConstant;
import com.classroom.smart.result.Result;
import com.classroom.smart.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

@RestController
@RequestMapping("/display")
public class DisplayController {
    @Autowired
    private VideoService videoService;

    @PostMapping("upload")
    public Result upload(@RequestPart("videoFile")MultipartFile videoFile){
        HashMap hashMap = new HashMap();
        try{
            if (videoFile!=null){
                String accessKeyId = "LTAI5tQqjmxN4FdQeweiSvMn";
                String accessKeySecret = "21xncpuDQxuHtSwnCzgNrmCaT0m5Ii";
                String title = videoFile.getOriginalFilename();
                String fileName = videoFile.getOriginalFilename();
                InputStream inputStream = videoFile.getInputStream();

                //1.上传视频的方法
                UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
                UploadVideoImpl uploader = new UploadVideoImpl();
                UploadStreamResponse response = uploader.uploadStream(request);
                System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
                if (response.isSuccess()) {
                    System.out.print("VideoId=" + response.getVideoId() + "\n");
                } else { //如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                    System.out.print("VideoId=" + response.getVideoId() + "\n");
                    System.out.print("ErrorCode=" + response.getCode() + "\n");
                    System.out.print("ErrorMessage=" + response.getMessage() + "\n");
                }
                String id = response.getVideoId();
                hashMap.put("id", id);
                hashMap.put("fileName", fileName);
                return new Result(true, MessageConstant.VIDEO_UPLOAD_SUCCESS,hashMap);
            }else {
                throw new RuntimeException("文件为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.VIDEO_UPLOAD_FAIL);
    }
}
